#!/bin/bash
set -exu

BUCKET=${1:-brave-rpm-nightly}
GPG_KEY_ID=${2:-4A1B4360}
GPG_KEY_SHORT_ID=${GPG_KEY_ID:(-8)}
KEY_NAME=keys.asc
KEY_FILE=/tmp/${KEY_NAME}
TMP_REPO=/tmp/rpm_repo

echo "%_signature gpg
%_gpg_path $HOME/.gnupg
%_gpg_name Brave Software
%_gpgbin /usr/bin/gpg" > ~/.rpmmacros

rm -rf $TMP_REPO
mkdir -pv $TMP_REPO/x86_64
if ! rpm --checksig dist/*.rpm | grep pgp; then
  ./tools/auto_rpm_sign
  rpm --checksig dist/*.rpm | grep pgp
fi
# Ensure the rpm has the correct signature before continuing
# NOTE: rpm displays the short key id, all lower case
rpm -v -K dist/*.rpm | grep "key ID ${GPG_KEY_SHORT_ID,,}: OK"

cp dist/*.rpm $TMP_REPO/x86_64/

for arch in $TMP_REPO/x86_64 ; do
	createrepo -v --deltas $arch/
done
for arch in $TMP_REPO/x86_64 ; do
	createrepo -v --update --deltas $arch/
done

gpg --export --armor ${GPG_KEY_ID} > ${KEY_FILE}
aws s3 cp ${KEY_FILE} s3://${BUCKET}/keys.asc
aws s3api put-object-acl --acl public-read --bucket ${BUCKET} --key ${KEY_NAME}
aws s3 sync --acl public-read $TMP_REPO/ s3://$BUCKET/
